#!/bin/bash
#k8s master 初始化脚本，kubeadm安装方式，运行脚本时注意检查158行和170行的内容是否为tab缩进，若是空格要还改为tab缩进，防止因复制原因报错。
#date:2023/09/21  author:wqf
#OS:centos7.9
function install_init (){
    #设置主机名
        hostnamectl set-hostname master
    
    #0.临时禁用selinux
        setenforce 0
    #1.永久关闭
        sed -i "s/SELINUX=enforcing/SELINUX=disabled/g" /etc/sysconfig/selinux
        sed -i "s/SELINUX=enforcing/SELINUX=disabled/g" /etc/selinux/config
    
    #2.关闭防火墙
        systemctl stop firewalld && systemctl disable firewalld
    
    #3.关闭swap
        swapoff -a
        sed -i 's/.*swap.*/#&/' /etc/fstab
    
    #4.提高同时打开文件/进程/内存限制
        ulimit -SHn 65535
 
        echo """
        * soft nofile 655350
        * hard nofile 655350
        * soft nproc 655350
        * hard nproc 655350
        * soft memlock unlimited
        * hard memlock unlimited
        """ >> /etc/security/limits.conf
 
        sed -i "s/* soft nproc 4096/* soft nproc 204800/g" /etc/security/limits.d/20-nproc.conf
        ulimit -a
    
    #5.配置内核参数
        echo """
        #禁止使用swap空间，只有当前系统OOM时才允许使用它
        vm.swappiness=0
        #不检查物理内存是否够用
        vm.overcommit_memory=1       
        #开启OOM
        vm.panic_on_oom=0       
        #开启网桥模式【重要】
        net.bridge.bridge-nf-call-iptables=1
        net.bridge.bridge-nf-call-ip6tables=1
        net.ipv4.ip_forward=1
        net.ipv4.ip_local_port_range = 1024 65535
        net.ipv4.tcp_max_tw_buckets = 6000
        net.ipv4.tcp_tw_recycle=0
        net.ipv4.tcp_tw_reuse=1
        net.ipv4.tcp_syn_retries=2
        net.ipv4.tcp_max_orphans = 327680
        net.ipv4.tcp_orphan_retries=3
        net.ipv4.tcp_fin_timeout=30
        net.ipv4.tcp_max_syn_backlog=16384
        net.ipv4.tcp_syncookies=1
        net.ipv4.tcp_keepalive_time=300
        net.ipv4.tcp_keepalive_probes=5
        net.ipv4.tcp_keepalive_intvl =15
        net.ipv4.tcp_timestamps = 0       
        #ipv6默认是开启状态
        #如实际项目不需使用ipv6时禁用
        net.ipv6.conf.default.disable_ipv6 = 0
        net.ipv6.conf.all.disable_ipv6 = 0
        net.ipv6.conf.lo.disable_ipv6 = 0
        net.ipv6.conf.all.forwarding = 1      
        net.core.netdev_max_backlog=3000
        net.core.somaxconn = 16384
        net.netfilter.nf_conntrack_max=2310720       
        fs.inotify.max_user_instances=8192
        fs.inotify.max_user_watches=1048576
        fs.file-max=52706963
        fs.nr_open=52706963
        """ > /etc/sysctl.d/kubernetes.conf

        modprobe bridge
        modprobe br_netfilter
        modprobe ip_conntrack
        sysctl -p /etc/sysctl.d/kubernetes.conf

    #6.关闭其他无用服务
        #关闭邮件服务
        systemctl stop postfix && systemctl disable postfix
        #关闭Dnsmasq
        systemctl stop dnsmasq && systemctl disable dnsmasq
        #关闭NetworkManager服务
        cat /etc/redhat-release |grep CentOS
        if [ $? -eq 0 ];then
            systemctl stop NetworkManager && systemctl disable NetworkManager
        else
            exit 1
        fi
    #7.设置日志保存方式
        mkdir /var/log/journal
        
        mkdir /etc/systemd/journald.conf.d
        
        echo "
        [Journal] 
        #持久化保存到磁盘 
        Storage=persistent 

        #压缩历史日志 
        Compress=yes 

        SyncIntervalSec=5m 
        RateLimitInterval=30s 
        RateLimitBurst=1000 

        #最大占用空间10G 
        SystemMaxUse=10G 

        #单日志文件最大200M 
        SystemMaxFileSize=200M 

        #日志保存时间2周 
        MaxRetentionSec=2week 

        #不将日志转发到syslog 
        ForwardToSyslog=no
        " >> /etc/systemd/journald.conf.d/99-prophet.conf 

        systemctl restart systemd-journald
    #8.开启IPVS
        echo " 
            #!/bin/bash
            modprobe -- ip_vs
            modprobe -- ip_vs_rr
            modprobe -- ip_vs_wrr
            modprobe -- ip_vs_sh

            modprobe -- nf_conntrack
            modprobe -- nf_conntrack_ipv4
            modprobe -- nf_conntrack_ipv6 ">> /etc/sysconfig/modules/ipvs.modules
        
        chmod 755 /etc/sysconfig/modules/ipvs.modules && bash /etc/sysconfig/modules/ipvs.modules && lsmod | grep -e ip_vs -e nf_conntrack

        #安装ipvadm管理工具
        yum install ipvsadm -y
        ipvsadm -ln
}

function install_docker (){
    #1.安装必要的一些系统工具
        yum install -y yum-utils device-mapper-persistent-data lvm2 expect

    #2.添加软件源信息
        yum-config-manager --add-repo http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo

    #3.更新并安装 Docker-CE
        yum makecache fast
        yum install -y docker-ce-20.10.18 docker-ce-cli-20.10.18 containerd.io

    #4.配置镜像加速
        mkdir /etc/docker
        cat > /etc/docker/daemon.json <<- EOF
        {
        "registry-mirrors": ["https://7e0znyhp.mirror.aliyuncs.com"]
        }
EOF
    #5.设置开机自启
        systemctl daemon-reload
        systemctl restart docker && systemctl enable docker
}

function install_master (){
    #1.添加阿里k8s源
        cat > /etc/yum.repos.d/kubernetes.repo <<- EOF
        [kubernetes]
        name=Kubernetes
        baseurl=https://mirrors.aliyun.com/kubernetes/yum/repos/kubernetes-el7-x86_64/
        enabled=1
        gpgcheck=1
        repo_gpgcheck=1
        gpgkey=https://mirrors.aliyun.com/kubernetes/yum/doc/yum-key.gpg https://mirrors.aliyun.com/kubernetes/yum/doc/rpm-package-key.gpg
EOF
    #2.安装kubeadm、kubeadm、kubelet
        yum makecache fast
        yum install kubelet-1.21.5 kubeadm-1.21.5 kubectl-1.21.5 -y

    #3.初始化安装
    #判断网卡名
        ip a | grep ens33
        if [ $? -eq 0 ];then
            ip=`ifconfig ens33 | grep "netmask" | awk -F" " '{print $2}'`
            kubeadm init \
            --apiserver-advertise-address=$ip \
            --image-repository=registry.aliyuncs.com/google_containers \
            --kubernetes-version=v1.21.5 \
            --control-plane-endpoint=$ip \
            --service-cidr=172.96.0.0/12 \
            --pod-network-cidr=172.244.0.0/16 \
            --v=5
        
        mkdir -p $HOME/.kube
        sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
        sudo chown $(id -u):$(id -g) $HOME/.kube/config

        else
            echo "网卡名错误，请检查"
        fi
}

#调用执行
function deploy (){
    install_init
    install_docker
    install_master
}
#执行入口
deploy
